package com.ruoyi.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.service.ClassPermissionsService;
import com.ruoyi.business.service.IWsdClassesService;
import com.ruoyi.business.service.IWsdRechargeRefundService;
import com.ruoyi.business.service.IWsdStudentsService;
import com.ruoyi.business.service.impl.WsdCanteenBalanceServiceImpl;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.dto.WsdStudentImportDTO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WsdCanteenBalance;
import com.ruoyi.common.core.domain.entity.WsdClasses;
import com.ruoyi.common.core.domain.entity.WsdStudents;
import com.ruoyi.common.core.domain.vo.RechargeRefundVO;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.date.DateTimeUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 学生信息Controller
 *
 * @author ruoyi
 * @date 2024-04-15
 */
@RestController
@RequestMapping("wsd_students")
public class WsdStudentsController extends BaseController
{
    @Autowired
    private IWsdStudentsService wsdStudentsService;
    @Autowired
    private ClassPermissionsService classPermissionsService;
    @Autowired
    private IWsdRechargeRefundService wsdRechargeRefundService;
    @Autowired
    private WsdCanteenBalanceServiceImpl wsdCanteenBalanceService;
    @Autowired
    private IWsdClassesService wsdClassesService;
    /**
     * 查询学生信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:students:list')")
    @GetMapping("/list")
    public TableDataInfo list(WsdStudents wsdStudents)
    {
        startPage();
        SysUser sysUser = getLoginUser().getUser();
        Long schoolId = sysUser.getSchoolId();
        //权限
        if (!sysUser.isAdmin()) {//过滤掉admin账号
            if (schoolId == null) {
                //没有绑定schoolId的返回空集合
                List<WsdStudents> emptyList = new ArrayList<>();
                return getDataTable( emptyList );
            }
            //if (wsdStudents.getClassId()==null){//当没有传classId时，查权限
                if (!"business".equals( sysUser.getRoles().get( 0 ).getRoleKey() )) {//过滤调学校管理员角色
                    String classIds = classPermissionsService.classIds();
                    wsdStudents.setClassIds( classIds );
                }
            //}
            wsdStudents.setSchoolId( schoolId );
        }
        List<WsdStudents> list = wsdStudentsService.selectWsdStudentsList(wsdStudents);
        for (WsdStudents wsdStudents1 : list){
            //当前学校的配置id
            Long schoolIds = wsdStudents1.getSchoolId();
            //获取配置ConfigId
            String currentDateString = DateTimeUtil.getCurrentDateString();
            RechargeRefundVO rechargeRefundVO = wsdRechargeRefundService.existsActiveSemester(schoolIds,currentDateString);
            if (rechargeRefundVO == null){
                wsdStudents1.setBreakfast( "未缴费" );
                wsdStudents1.setLunch( "未缴费" );
                wsdStudents1.setDinner( "未缴费" );
            }else {
                //查询余额表
                LambdaQueryWrapper<WsdCanteenBalance> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq( WsdCanteenBalance::getStudentId, wsdStudents1.getId() )
                        .eq( WsdCanteenBalance::getConfigId, rechargeRefundVO.getConfigId() )
                        .eq( WsdCanteenBalance::getSchoolId, wsdStudents1.getSchoolId() );
                // 查询学生在该学校的余额记录
                WsdCanteenBalance balance = wsdCanteenBalanceService.getOne( queryWrapper, false );
                if (balance == null) {
                    wsdStudents1.setBreakfast( "未缴费" );
                    wsdStudents1.setLunch( "未缴费" );
                    wsdStudents1.setDinner( "未缴费" );
                } else {
                    // 设置早餐缴费状态
                    wsdStudents1.setBreakfast(
                            balance.getTotalRechargeAmountBreakfast().compareTo( BigDecimal.ZERO ) > 0 ? "已缴费" : "未缴费"
                    );
                    wsdStudents1.setLunch(
                            balance.getTotalRechargeAmountLunch().compareTo( BigDecimal.ZERO ) > 0 ? "已缴费" : "未缴费"
                    );
                    wsdStudents1.setDinner(
                            balance.getTotalRechargeAmountDinner().compareTo( BigDecimal.ZERO ) > 0 ? "已缴费" : "未缴费"
                    );
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出学生信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:students:export')")
    @Log(title = "学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WsdStudents wsdStudents)
    {
        List<WsdStudents> list = wsdStudentsService.selectWsdStudentsList(wsdStudents);
        ExcelUtil<WsdStudents> util = new ExcelUtil<WsdStudents>(WsdStudents.class);
        util.exportExcel(response, list, "学生信息数据");
    }

    /**
     * 获取学生信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:students:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(wsdStudentsService.selectWsdStudentsById(id));
    }

    /**
     * 新增学生信息
     */
    @PreAuthorize("@ss.hasPermi('business:students:add')")
    @Log(title = "学生信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WsdStudents wsdStudents)
    {
        if (wsdStudents.getClassId()==null){
            return AjaxResult.error("新增学生失败，班级信息为空！！");
        }
        SysUser sysUser = getLoginUser().getUser();
        Long schoolId = sysUser.getSchoolId();
        if (schoolId == null) {
            return AjaxResult.error("新增学生失败，学校信息为空！！");
        }
        wsdStudents.setSchoolId( schoolId );
        return toAjax(wsdStudentsService.insertWsdStudents1(wsdStudents));
    }

    /**
     * 修改学生信息
     */
    @PreAuthorize("@ss.hasPermi('business:students:edit')")
    @Log(title = "学生信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WsdStudents wsdStudents)
    {
        return toAjax(wsdStudentsService.updateWsdStudents(wsdStudents));
    }

    /**
     * 删除学生信息
     */
    @PreAuthorize("@ss.hasPermi('business:students:remove')")
    @Log(title = "学生信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(wsdStudentsService.deleteWsdStudentsByIds(ids));
    }

    // 导入方法
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(@RequestParam("file") MultipartFile file
                                 ) throws Exception
    {
//        if (classId==null){
//            return AjaxResult.error( "班级信息为空，请选择班级后重新上传！！！" );
//        }
        if (file.isEmpty()){
            return AjaxResult.error( "文件为空，请重新上传！！！" );
        }
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            return AjaxResult.error( "文件解析失败，请重新上传！！！" );
        }
        WsdClasses wsdClasses = new WsdClasses();
//        WsdClasses wsdClasses = wsdClassesService.selectWsdClassesById(classId);
//        if (wsdClasses==null){
//            return AjaxResult.error( "班级信息为空，请选择班级后重新上传！！！" );
//        }
        ExcelUtil<WsdStudentImportDTO> util = new ExcelUtil<WsdStudentImportDTO>(WsdStudentImportDTO.class);
        List<WsdStudentImportDTO> userList = util.importExcel(inputStream);
        AjaxResult result = wsdStudentsService.importData(userList,wsdClasses.getId(),wsdClasses.getSchoolId());
        return result;
    }
}
